package com.luban.springcloud.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.luban.springcloud.pojo.User;
import com.luban.springcloud.service.UserService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

@RestController
@RequestMapping("/user")
public class UserProviderController {
	
	@Autowired
	private UserService userService;
	
	/**
	 * 新增或者修改用户信息
	 * @param user
	 * @return
	 */
	@PostMapping(value="/adOrUp")
	public Object addOrUpdateUser(@RequestBody User user) {
		return	userService.addOrUpdateUser(user);
	}
	
	/**
	 * 根据id查询用户
	 * @param id
	 * @return
	 * @throws JsonProcessingException 
	 */
	@GetMapping(value="/get/{id}")
	public Object findUserById(@PathVariable("id")Integer id){
		System.out.println("----服务提供者5000-----");
		return	userService.findUserById(id);
	}
	
	/**
	 * 查询所有用户
	 * @return
	 */
	@GetMapping(value="/list")
	public List<User> list(){
		return userService.listUser();
	}
	
	/**
	 * 根据id删除用户
	 * @param id
	 * @return
	 */
	@GetMapping(value="/delete/{id}")
	public boolean delete(@PathVariable("id")Integer id) {
		try {
			userService.deleteUser(id);
			return true; 
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	 /**
	 * 测试Hystrix服务熔断服务降级
	 * @return
	 * @throws InterruptedException 
	 */
	@GetMapping(value="/getTestInfo")
	@HystrixCommand(fallbackMethod="getTestInfoFallback")
	public Map<String,Object> getTestInfo() throws InterruptedException{
	    Thread.sleep(200);
	    Map<String,Object> map=new HashMap<String,Object>();
	    map.put("code", 200);
	    map.put("info", "服务者提供消息正常");
	    return map;
	}
	 
	public Map<String,Object> getTestInfoFallback() throws InterruptedException{
	    Map<String,Object> map=new HashMap<String,Object>();
	    map.put("code", 500);
	    map.put("info", "服务者提供消息发生错误");
	    return map;
	}
	
	@GetMapping(value="/getServiceInfo")
	public Map<String, Object> getServiceInfo() throws InterruptedException{
		 Thread.sleep(500);
		 return userService.getServiceInfo();
	}
}
